//
// Created by yyl on 2018/6/5.
//

#include "OnCallBack.h"
#include "../yyl_log.h"

OnCallBack::OnCallBack(JNIEnv *env1, jobject jobject1) {
    this->jniEnv = env1;
    this->javaObject = jobject1;
    jint result = env1->GetJavaVM(&this->javaVM);
//    LOGI("javaVM reslut=%d", result);
    jclass clazz = jniEnv->GetObjectClass(jobject1);
    if (!clazz) {
        return;
    }
    this->javaCallBackPrint = jniEnv->GetMethodID(clazz,
                                                  "onCallBackPrint",
                                                  "(Ljava/lang/String;)V");
}

void OnCallBack::onCallBackPrint(int threadType, const char *msg) {
    if (threadType == 0) {//子线程
        JNIEnv *env;
        javaVM->AttachCurrentThread(&env, 0);
        jstring message = env->NewStringUTF(msg);//这里必须在主线程中调用
        env->CallVoidMethod(javaObject, javaCallBackPrint, message);
        env->DeleteLocalRef(message);
        javaVM->DetachCurrentThread();
    } else if (threadType == 1) {//主线程
        jstring message = jniEnv->NewStringUTF(msg);
        jniEnv->CallVoidMethod(javaObject, javaCallBackPrint, message);
        jniEnv->DeleteLocalRef(message);
    }
}

OnCallBack::~OnCallBack() {

}
